import axios from "axios";
import { isDev } from "./helper";
import { getConfig } from "./configAction";

const request = axios.create({
  baseURL: isDev() ? "" : "/api",
  timeout: 2000
});

request.interceptors.response.use(
  function(response) {
    const { status, headers } = response;
    if (status >= 400) {
      return Promise.reject(response);
    }
    if (headers.hasOwnProperty("token")) {
      response.data.token = headers.token;
    }
    return response;
  },
  function(error) {
    const { response } = error;
    return Promise.reject(response);
  }
);

export default class Http {
  /**
   * post请求
   * @param {string} url 请求URL
   * @param {object} data 发送的数据
   * @param {boolean|object} loading loading=>是否显示加载中 params=>get参数
   * @param  {...any} args 其他参数
   */
  static post(url, data = {}, loading = false, ...args) {
    let options = {};
    if (!!loading && typeof loading === "object") {
      options = loading;
      loading = false;
      if (args.length && typeof args[0] === "boolean") {
        loading = args[0];
      }
    }
    if (options.headers && !options.headers.token) {
      options.headers.token = getConfig("token") || "";
    }
    return request.post(url, data, options);
  }

  /**
   * get请求
   * @param {string} url 请求URL
   * @param {object} data 发送的数据
   * @param {boolean} loading 是否显示加载中
   * @param  {...any} args 其他参数
   */
  static get(url, data, loading = false, ...args) {
    let options = {};
    if (!!loading && typeof loading === "object") {
      options = loading;
      loading = false;
      if (args.length && typeof args[0] === "boolean") {
        loading = args[0];
      }
    }
    if (typeof options.params === "object") {
      const { params } = options;
      Object.assign(data, params);
      delete options.params;
    }

    return request.get(url, {
      headers: { token: getConfig("token") || "" },
      params: data
    });
  }
}
